<template>
  <div ref="chartDom" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, defineProps, watch } from 'vue';
import * as echarts from 'echarts';

const chartDom = ref(null);
const props = defineProps({
  option: {
    type: Object,
    required: true,
    default: {
      xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [120, 200, 150, 80, 70, 110, 130],
          type: 'bar',
          showBackground: true,
        }
      ]
    }
  }
});
let chartInstance = null;

onMounted(() => {
  chartInstance = echarts.init(chartDom.value);
  chartInstance.setOption(props.option);
  window.addEventListener('resize', handleResize); // 响应窗口变化
});

watch(() => props.option, (newOption) => {
  if (chartInstance && newOption) {
    chartInstance.setOption(newOption);
  }
}, { deep: true });
const handleResize = () => {
  chartInstance?.resize();
};

onUnmounted(() => {
  chartInstance?.dispose();
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.chart-container {
  width: 100%; /* 默认占满父容器 */
  height: 100%; /* 默认高度，可被外部覆盖 */
}
</style>
